package util;

import java.sql.*;

public class JDBCConnection {
    private final static String dbDriver="com.mysql.jdbc.Driver";
    private final static String url = "jdbc:mysql://120.25.197.135:3306/parking?autoReconnect=true";
    private final static String userName = "root";
    private final static String password = "RootPass";
    private Connection con = null;
    //开始时执行
    static {
        try {
            Class.forName(dbDriver);
        } catch (Exception ex) {
            System.out.println("JDBC static error  ："+ex);
        }
    }
    //
    private boolean createConnection() {
        try {
            con = DriverManager.getConnection(url, userName, password);
            con.setAutoCommit(true);

        } catch (SQLException e) {
            System.out.println(e.getMessage());
            System.out.println("creatConnectionError!");
        }
        return true;
    }
    //update
    public boolean executeUpdate(String sql) {
        if (con == null) {
            createConnection();
        }
        try {
            Statement stmt = con.createStatement();
            int iCount = stmt.executeUpdate(sql);
            System.out.println("" + String.valueOf(iCount));
            return true;
        } catch (SQLException e) {
            System.out.println(e.getMessage());
            return false;
        }
    }
    //select
    public ResultSet executeQuery(String sql) {
        ResultSet rs;
        try {
            if (con == null) {
                createConnection();
            }
            Statement stmt = con.createStatement();
            try {
                rs = stmt.executeQuery(sql);
            } catch (SQLException e) {
                System.out.println(e.getMessage());
                return null;
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
            System.out.println("executeQueryError!");
            return null;
        }
        return rs;
    }
}
